<?php
/**
 * Created by PhpStorm.
 * User: 17274
 * Date: 2018/3/27
 * Time: 21:06
 */
namespace app\admin\model\novel;

use app\admin\helper\DBhelper;
use app\admin\helper\LangHelper;
use app\admin\helper\SearchHelper;
use app\admin\model\BaseM;
use app\admin\model\LogsM;
use app\admin\popo\LayData;
use think\Config;
use think\Session;
use think\Validate;

class NovelM extends  BaseM
{
    protected $table = 'tb_novel';
    protected $module = '小说列表';

    /*
     * rule
     * 验证data
     * @params $data
     * 新增和修改时验证
     * */
    public function validate_model(){
        $post = input('post.');
        $rule = [
            'title' => 'require',
            'brief' => 'require',
            'author' => 'require',
        ];
        $msg = [
            'title.require' => '__novel.validata.title.require__',
            'brief.require' => '__validata.brief.require__',
            'author.require' => '__validata.author.require__'
        ];
        if (empty($post['id'])) {
            $rule['title'] = 'unique:novel|require';
            $msg['title.unique'] = '__novel.validata.title.unique__';
        }

        $msg = LangHelper::convertLang($msg,'field');
        $validate = new Validate($rule, $msg);
        $result = $validate->check($post);
        if(!$result){
            return op_msg(0,$validate->getError());
        }
        return op_msg(1,'success');
    }

    /**
     * 前端search控件
     * button vale [ add edit del search export ]
     * @return mixed
     */
    public function __search(){
        $search = [
            'tag'=>['field'=>'tag','title'=>'__tag__','type'=>'input','value'=>''],
            'status'=>['field'=>'status','title'=>'__novel_status__','type'=>'select','value'=>'function:getNovelStatusList'],
            'created_at'=>['field'=>'created_at','title'=>'__created_at__','type'=>'date_range','value'=>'function:getMonthDateRange'],
            'button'=>['type'=>'button','value'=>['add','search','export']],
        ];
        SearchHelper::convertValue($search);
        $search['form'] = implode(',',array_keys($search));
        return LangHelper::convertLang($search,'field');
    }

    /**
     * 前端表格列
     * @return string
     */
    public function __header(){
        $header = [
            ['type'=>'checkbox'],
            ['field'=>'title','title'=>'__novel.title__'],
            ['field'=>'brief','title'=>'__brief__','width'=>80,'style'=>'text-align:center'],
            ['field'=>'author','title'=>'__author__'],
            ['field'=>'icon','title'=>'__novel.icon__','width'=>80,'style'=>'text-align:center'],
            ['field'=>'hits','title'=>'__hits__'],
            ['field'=>'likes','title'=>'__likes__'],
            ['field'=>'tags_name','title'=>'__tags__'],
            ['field'=>'novel_status_name','title'=>'__novel_status__'],
            ['field'=>'last_chapter','title'=>'__last_chapter__'],
            ['field'=>'created_at','title'=>'__created_at__','width'=>150],
            ['field'=>'updated_at','title'=>'__updated_at__','width'=>150],
            ['field'=>'op','title'=>'__op__','toolbar'=>'#operate']
        ];
        return json_encode(LangHelper::convertLang($header,'field'));
    }

    /*
     * 列表
     * */
   public function listData($taglist){
       $page=input("post.page/d");
       $limit=input("post.limit/d");
       $tag=input("post.tag/s");
       $time=input("post.created_at/s");
       $start = strtotime(explode(' - ',$time)[0]);
       $end = strtotime(explode(' - ',$time)[1]);

       $where = [
           'title|brief|author|tags'=>['like',"%".$tag."%"],
           'created_at'=>['between', [$start, $end+86399]]
       ];
       $status=input("post.status/d");
       if ($status>0) {
           $where['novel_status'] = $status;
       }

       $novelChapterM = new NovelChapterM();

       $log = [
           'op_uid' => Session::get('username'),
           'op_module' => $this->module,
           'op_type' => 'search',
           'op_origin' => $this->table,
           'op_data' => json_encode($where,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),
           'op_ip' => getIP(),
       ];
       $status_list = SearchHelper::getNovelStatusList();
       //export逻辑
       if (input("post.export/b")) {
           $header = json_decode($this->__header(),true);
           $export_data = $this->where($where)->order('id desc')->select();
           foreach ($export_data as $k=>$v) {
               $export_data[$k]->novel_status_name = $status_list[$v->novel_status];
               if (!empty($v->tags)){
                   $tags = explode(',',$v->tags);
                   $tagsName = [];
                   foreach ($tags as $tag) {
                       $tagsName[] = isset($taglist[$tag])?$taglist[$tag]:'null';
                   }
                   $export_data[$k]->tags_name = implode(',',$tagsName);
               }
               $export_data[$k]['last_chapter'] = $novelChapterM->getLast($export_data[$k]->id);
           }

           $log['op_sql'] = $this->getLastSql();
           $log['op_type'] = 'export';
           $log['op_data'] = json_encode($header,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
           LogsM::add($log);
           pr_log($log,'operate');
           export('小说列表',$export_data->toArray(),$header);
       }

       $resp = new LayData();
       $resp->count = $this->where($where)->count();
       $resp->data = $this->where($where)->order('id desc')->page($page,$limit)->select();

       foreach ($resp->data as $k=>$v) {
           $resp->data[$k]->novel_status_name = $status_list[$v->novel_status];
           if (!empty($v->tags)){
               $tags = explode(',',$v->tags);
               $tagsName = [];
               foreach ($tags as $tag) {
                   $tagsName[] = isset($taglist[$tag])?$taglist[$tag]:'null';
               }
               $resp->data[$k]->tags_name = implode(',',$tagsName);
           }
           $resp->data[$k]['last_chapter'] = $novelChapterM->getLast($resp->data[$k]->id);
           //hits计算 各章节浏览量相加
           $resp->data[$k]['hits'] = $novelChapterM->getHits($resp->data[$k]->id);
           //likes计算 各章节ip去重(小说章节下)
           $resp->data[$k]['likes'] = $novelChapterM->getLikes($resp->data[$k]->id);
       }
       $resp->extra_data = Config::get('app_debug')?$this->getLastSql():'';
       $log['op_sql'] = $this->getLastSql();
       LogsM::add($log);
       pr_log($log,'operate');
       return $resp;
   }

    /**
 * list All Data  status=1
 * @return false|\PDOStatement|string|\think\Collection
 */
    public function listAll(){
        return $this->field('id,title')->order('created_at desc')->select();
    }

    /*
     * 新增
     * */
    public function add(){
        $data=input('post.');
        unset($data['method']);
        $data['created_at']=time();
        $data['updated_at']=time();
        $re = $this->save($data);
        $last_sql = Config::get('app_debug')?$this->getLastSql():'';
        if($re){
            $log = [
                'op_uid' => Session::get('username'),
                'op_module' => $this->module,
                'op_type' => 'add',
                'op_origin' => $this->table,
                'op_data' => $data['title'],
                'op_ip' => getIP(),
                'op_sql' => $this->getLastSql(),
            ];
            LogsM::add($log);
            pr_log($log,'operate');
            return op_success($last_sql);
        }
        return op_fail($last_sql);
    }

    /*
     * 修改
     * */
    public function edit(){
        $data=input('post.');
        $id=$data['id'];
        unset($data['method']);
        //只修改变化字段
        $origin = $this->getById($id)->toArray();
        $data = DBhelper::getChangeData($data,$origin);
        if (!empty($data)){
            $data['updated_at']=time();
            $re = $this->where('id',$id)->update($data);
            $last_sql = Config::get('app_debug')?$this->getLastSql():'';
            if($re){
                //删除替换的图片
                if (!empty($data['ab_icon']))
                    unlink($origin['ab_icon']);
                $log = [
                    'op_uid' => Session::get('username'),
                    'op_module' => $this->module,
                    'op_type' => 'edit',
                    'op_origin' => $this->table,
                    'op_data' => json_encode($data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),
                    'op_ip' => getIP(),
                    'op_sql' => $this->getLastSql(),
                ];
                LogsM::add($log);
                pr_log($log,'operate');
                return op_success($last_sql);
            }
            return op_fail($last_sql);
        }
        return op_nochange();
    }

    /*
     * 删除
     * */
    public function del(){
        $ids=input('post.ids/a');
        $op_name=[];
        foreach ($ids as $id){
            $name = $this->getById($id)->toArray()['title'];
            array_push($op_name,$name);
        }
        if (!empty($op_name)) {
            //事务开始
            $this->startTrans();
            $re = $this->destroy($ids);
            $last_sql = Config::get('app_debug')?self::getLastSql():'';
            if ($re){
                //删除相应卷 相应章节
                if (NovelVolumeM::delByNoveId($ids)) {
                    $this->commit();
                    $log = [
                        'op_uid' => Session::get('username'),
                        'op_module' => $this->module,
                        'op_type' => 'delete',
                        'op_origin' => $this->table,
                        'op_data' => json_encode($op_name,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),
                        'op_ip' => getIP(),
                        'op_sql' => $this->getLastSql(),
                    ];
                    LogsM::add($log);
                    pr_log($log,'operate');
                    return op_success($last_sql);
                }
            }
            $this->rollback();
            return op_fail($last_sql);
        }
        return op_superadmin();
    }

}